package com.zat.mes.andrmes.dofun.qualitytest

import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.data.QcRecordBean
import com.zat.mes.andrmes.dofun.qualitytest.adapter.QcRecordOnsiteAdapter
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.dofun.work.vm.WorkRecordViewModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.SpannableStrUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_on_site.*
import kotlinx.android.synthetic.main.item_quality_plan.view.*
import kotlinx.android.synthetic.main.layout_title.*

/**
 * 扫码进巡检
 */
class OnSiteActivity : BaseActivity() {

    private var packBean: PackBean? = null
    private var empId: Long = 0
    private var qcPlanViewModel: QcPlanViewModel? = null
    var adapter: QcRecordOnsiteAdapter? = null
    override fun init() {
        initView()
        iniData()
    }

    private fun iniData() {
        //二维码
        val qrCode = intent.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE);
        //rfId 刷卡
        val rfId = intent.getStringExtra(CompanionType.INTENT_EXTRA_RFID);
        var type = intent.getIntExtra(CompanionType.INTENT_EXTRA_QCTYPE, 0);
        if (type == 0) {
            tVtitle.text = getString(R.string.title_quality_text)
        } else {
            tVtitle.text = getString(R.string.title_on_site)
        }
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        adapter = QcRecordOnsiteAdapter(R.layout.item_item_quality_plan, type)
        recyclerOnSite.layoutManager = LinearLayoutManager(this)
        recyclerOnSite.adapter = adapter
        qcPlanViewModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcPlanViewModel?.getQcWorkRecordData()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                setUi(it)
            }
        })
        val workRecordViewModel = ViewModelProvider(this).get(WorkRecordViewModel::class.java)
        workRecordViewModel.getPackData().observe(this, Observer {
            closeLoading()
            if (it == null) {
                showToast(getString(R.string.text_not_find_pack))
            } else {
                packBean = it
                requestList()
            }

        })
        if (!TextUtils.isEmpty(qrCode)) {
            //二维码请求包
            workRecordViewModel.loadPackDataQc(qrCode)
        }

        if (!TextUtils.isEmpty(rfId)) {
            //刷卡
            workRecordViewModel.loadPackDataByRFRDQc(rfId)
        }
        showLoading()

        adapter?.setOnItemClickListener { adapter, view, position ->
            val item: QcRecordBean = adapter.getItem(position) as QcRecordBean
            if ("3".equals(item?.status)) {
                //未完成
                val intent = Intent(this, OnSiteDetailActivity::class.java)
                intent.putExtra(CompanionType.INTENT_EXTRA_BEAN, item)
                intent.putExtra(
                    CompanionType.INTENT_EXTRA_QCTYPE,
                    getIntent().getIntExtra(CompanionType.INTENT_EXTRA_QCTYPE, 0)
                )
                try {
                    startActivityForResult(intent, 101)

                } catch (e: Exception) {
                    Log.e("activity", e.toString())
                }

            } else if ("5".equals(item?.status)) {
                //已经完成
                val intent = Intent(this, OnSiteHasActivity::class.java)
                intent.putExtra(CompanionType.INTENT_EXTRA_QCID, item?.xjId)
                startBaseActivity(intent)
            }
        }

    }

    /**
     * 请求列表
     */
    private fun requestList() {
        if (packBean != null) {
            packBean?.orderId?.let {
                packBean?.packId?.let { it1 ->

                    qcPlanViewModel?.loadQcWorkRecord(
                        empId,
                        it, it1, packBean?.clothsqRcode, packBean?.clothsRFIDcode
                    )

                }
            }
            showLoading()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            android.os.Handler().postDelayed(Runnable { requestList() }, 1000)
        }
    }

    private fun setUi(list: MutableList<QcRecordBean>) {

        val headerView = LayoutInflater.from(this).inflate(R.layout.item_quality_plan, null)
        headerView.dwLayoutItemQuality.setLineColor(
            ContextCompat.getColor(
                baseContext,
                R.color.color_transparent
            )
        )
        if (!adapter?.hasHeaderLayout()!!) {
            adapter?.addHeaderView(headerView)
        }
        adapter?.setNewData(list)
        if (list != null && list.size > 0) {
            val qcRecordBean = list.get(0)
            headerView.tvNameQualityPlanItem.text = qcRecordBean?.productName
            headerView.llBtnQualityPlanShowHide.visibility = View.GONE

            var styleNo = getString(R.string.text_style) + " " + qcRecordBean?.styleNO
            var color = getString(R.string.text_color) + " " + qcRecordBean?.color
            var size = getString(R.string.text_size) + " " + qcRecordBean?.size
            val textColor = ContextCompat.getColor(this, R.color.color_text_grey)
            headerView.tvStyleNoQualityPlanItem.text =
                SpannableStrUtil.getColorSpannable(styleNo, 3, styleNo.length, textColor)

            headerView.tvColorQualityPlanItem.text =
                SpannableStrUtil.getColorSpannable(color, 3, color.length, textColor)

            headerView.tvSizeQualityPlanItem.text =
                SpannableStrUtil.getColorSpannable(size, 3, size.length, textColor)

        }
    }

    private fun initView() {
        setContentView(R.layout.activity_on_site)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }
    }


}
